package fr.dauphine.bookstore.frontoffice;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;

import fr.dauphine.bookstore.modele.Book;
import fr.dauphine.bookstore.modele.Order;

/**
 * Modification de la quantite d'un livre dans le panier.
 */
public final class ModifyQuantityServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 8738299506492709905L;

	/**
	 * Traite la methode GET.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		Long id = Long.valueOf(request.getParameter("id"));
		String type = request.getParameter("type");
		Order order = SessionUtil.getOrder(request.getSession());

		Book book = (Book) CollectionUtils.find(order.getBooks().keySet(), new BeanPropertyValueEqualsPredicate("id", id));

		if (book != null) {
			Integer quantity = order.getBooks().get(book);

			if ("plus".equals(type)) {
				order.getBooks().put(book, quantity + 1);

			} else if (quantity == 1) {
				order.getBooks().remove(book);

			} else {
				order.getBooks().put(book, quantity - 1);
			}
		}

		// Le panier est vide,
		// On le supprime pour alleger la session
		if (order.getBooks().isEmpty()) {
			SessionUtil.removeOrder(request.getSession());

		} else {
			SessionUtil.setOrder(request.getSession(), order);
		}

		response.sendRedirect("panier.jsp");
	}
}
